// WebSocketManager.ts
type EventHandler = (data: string) => void;

export class WebSocketManager {
    // 单例实例
    private static instance: WebSocketManager;
    // 存储不同标识符对应的WebSocket连接
    private connections: { [key: string]: WebSocket } = {};
    // 存储事件监听器
    private eventListeners: { [identifier: string]: EventHandler[] } = {};

    // 私有构造函数，防止外部实例化
    private constructor() {}

    // 获取单例实例的静态方法
    public static getInstance(): WebSocketManager {
        if (!this.instance) {
            this.instance = new WebSocketManager();
        }
        return this.instance;
    }

    // 建立WebSocket连接
    public connect(identifier: string, url: string): void {
        if (this.connections[identifier]) {
            console.warn(`WebSocket connection with identifier "${identifier}" already exists.`);
            return;
        }

        const ws = new WebSocket(url);

        // 添加事件监听器
        ws.addEventListener('open', () => {
            console.log(`WebSocket connection "${identifier}" opened.`);
        });

        ws.addEventListener('message', (event) => {
            console.log(`Received message from WebSocket "${identifier}":`, event.data);
            this.dispatchEvent(identifier, event.data as string);
        });

        ws.addEventListener('close', () => {
            console.log(`WebSocket connection "${identifier}" closed.`);
            delete this.connections[identifier];
            delete this.eventListeners[identifier];
        });

        ws.addEventListener('error', (error) => {
            console.error(`WebSocket connection "${identifier}" error:`, error);
            delete this.connections[identifier];
            delete this.eventListeners[identifier];
        });

        // 存储连接
        this.connections[identifier] = ws;
    }

    // 注册事件监听器
    public on(identifier: string, handler: EventHandler): void {
        if (!this.eventListeners[identifier]) {
            this.eventListeners[identifier] = [];
        }
        this.eventListeners[identifier].push(handler);
    }

    // 分发事件
    private dispatchEvent(identifier: string, data: string): void {
        const handlers = this.eventListeners[identifier];
        if (handlers) {
            handlers.forEach((handler) => handler(data));
        }
    }

    // 发送消息到指定的WebSocket连接
    public send(identifier: string, message: string): void {
        const ws = this.connections[identifier];
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(message);
        } else {
            console.warn(`WebSocket connection "${identifier}" is not open or does not exist.`);
        }
    }

    // 关闭指定的WebSocket连接
    public close(identifier: string): void {
        const ws = this.connections[identifier];
        if (ws) {
            ws.close();
            delete this.connections[identifier];
            delete this.eventListeners[identifier];
        } else {
            console.warn(`WebSocket connection "${identifier}" does not exist.`);
        }
    }

    // 关闭所有WebSocket连接
    public closeAll(): void {
        for (const identifier in this.connections) {
            this.close(identifier);
        }
    }
}